<template>
  <div class="bg-white rounded-lg shadow-lg p-6">
    <h2 class="text-2xl font-bold text-gray-800 mb-4">示 例</h2>
    
    <!-- 示例网格 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div 
        v-for="example in examples" 
        :key="example.id"
        @click="selectExample(example)"
        :class="getHourClass(example.description)"
        class="rounded-lg p-6 cursor-pointer transition-all duration-300 hover:shadow-lg hover:scale-105 border border-gray-200"
      >
        <div class="flex items-start justify-between mb-3">
          <h3 class="text-lg font-semibold text-gray-800 leading-tight">{{ example.title }}</h3>
          <span 
            :class="getTypeClass(example.type)"
            class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap ml-2"
          >
            {{ example.type }}
          </span>
        </div>
        
        <p class="text-gray-600 text-sm mb-4 line-clamp-2">{{ example.description }}</p>
        
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-2">
            <span class="text-xs text-gray-500">难度:</span>
            <span class="text-xs font-medium" :class="getDifficultyClass(example.difficulty)">
              {{ getDifficultyText(example.difficulty) }}
            </span>
          </div>
          <div class="text-xs text-gray-500">
            {{ example.fileName }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useAssignmentStore } from '@/stores/assignment'

interface Example {
  id: string
  title: string
  description: string
  type: string
  difficulty: 'easy' | 'medium' | 'hard'
  fileName: string
  filePath: string
}

import type { SourceType } from '@/stores/assignment'

interface Props {
  examples: Example[]
  chapterName?: SourceType
}

const props = withDefaults(defineProps<Props>(), {
  chapterName: 'examples' as SourceType
})

const router = useRouter()
const assignmentStore = useAssignmentStore()

const selectExample = async (example: Example) => {
  try {
    const response = await fetch(example.filePath)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const content = await response.text()

    // 记录当前路由作为返回路径
    const currentRoute = router.currentRoute.value
    const returnRoute = {
      path: currentRoute.path,
      query: currentRoute.query
    }

    // 设置示例到store，并记录返回路由
    assignmentStore.setCurrentExample({
      id: example.id,
      title: example.title,
      description: example.description,
      content: content,
      filePath: example.filePath,
      fileName: example.fileName
    }, props.chapterName, returnRoute)

    // 跳转到编辑器
    // router.push('/editor')
    router.push('/sample')
  } catch (error) {
    console.error('加载示例文件失败:', error)
    alert('加载示例文件失败，请检查文件路径')
  }
}

const getTypeClass = (type: string) => {
  const classes: Record<string, string> = {
    '基础模板': 'bg-blue-100 text-blue-800',
    '环境配置': 'bg-green-100 text-green-800',
    '应用创建': 'bg-purple-100 text-purple-800',
    '数据绑定': 'bg-yellow-100 text-yellow-800',
    '渐进式': 'bg-indigo-100 text-indigo-800',
    '响应式': 'bg-indigo-100 text-indigo-800',
    '实际应用': 'bg-pink-100 text-pink-800',
    '选项式API': 'bg-orange-100 text-orange-800',
    '组合式API': 'bg-red-100 text-red-800',
    'MVVM模式': 'bg-gray-100 text-gray-800',
    '前端开发环境': 'bg-cyan-100 text-cyan-800',
    '工具介绍': 'bg-teal-100 text-teal-800'
  }
  return classes[type] || 'bg-gray-100 text-gray-800'
}

const getDifficultyText = (difficulty: string) => {
  const texts = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return texts[difficulty as keyof typeof texts]
}

const getDifficultyClass = (difficulty: string) => {
  const classes = {
    easy: 'text-green-600',
    medium: 'text-yellow-600',
    hard: 'text-red-600'
  }
  return classes[difficulty as keyof typeof classes]
}

const getHourClass = (description: string) => {
  // 从描述中提取学时信息
  const hourMatch = description.match(/\[第(\d+)学时\]/)
  if (!hourMatch) {
    return 'bg-gradient-to-br from-gray-50 to-gray-100'
  }
  
  const hour = parseInt(hourMatch[1])
  const hourClasses = {
    1: 'bg-gradient-to-br from-blue-50 to-blue-100',
    2: 'bg-gradient-to-br from-green-50 to-green-100', 
    3: 'bg-gradient-to-br from-yellow-50 to-yellow-100',
    4: 'bg-gradient-to-br from-purple-50 to-purple-100'
  }
  
  return hourClasses[hour as keyof typeof hourClasses] || 'bg-gradient-to-br from-gray-50 to-gray-100'
}
</script>

<style scoped>
.bg-gradient-to-br {
  background: linear-gradient(to bottom right, var(--tw-gradient-stops));
}

/* 第1学时 - 蓝色系 */
.from-blue-50 {
  --tw-gradient-from: #eff6ff;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(239, 246, 255, 0));
}

.to-blue-100 {
  --tw-gradient-to: #dbeafe;
}

/* 第2学时 - 绿色系 */
.from-green-50 {
  --tw-gradient-from: #f0fdf4;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(240, 253, 244, 0));
}

.to-green-100 {
  --tw-gradient-to: #dcfce7;
}

/* 第3学时 - 黄色系 */
.from-yellow-50 {
  --tw-gradient-from: #fefce8;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(254, 252, 232, 0));
}

.to-yellow-100 {
  --tw-gradient-to: #fef3c7;
}

/* 第4学时 - 紫色系 */
.from-purple-50 {
  --tw-gradient-from: #faf5ff;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(250, 245, 255, 0));
}

.to-purple-100 {
  --tw-gradient-to: #e9d5ff;
}

/* 默认 - 灰色系 */
.from-gray-50 {
  --tw-gradient-from: #f9fafb;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(249, 250, 251, 0));
}

.to-gray-100 {
  --tw-gradient-to: #f3f4f6;
}

.transform {
  transform: var(--tw-transform);
}

.hover\:scale-105:hover {
  --tw-scale-x: 1.05;
  --tw-scale-y: 1.05;
  transform: translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>